package view.models;

import java.util.Date;
import java.util.Observable;
import java.util.Observer;

import javax.swing.table.AbstractTableModel;

import domain.Copy;
import domain.Customer;
import domain.Library;
import domain.Loan;

@SuppressWarnings("serial")
public class LoansPerCustomerTable extends AbstractTableModel implements Observer, LoanTableInterface {
	private Library lib = Library.getInstance();
	private String[] columnNames = new String[]{"Exemplar", "Titel", 
			"von", "bis", "Status"};
	private int[] searchColumns = {0, 1};
	private Customer customer;

	public LoansPerCustomerTable(Customer customer) {
		this.customer = customer;
		lib.addObserver(this);
		
		for(Loan l:lib.getCustomerLoans(customer)){
			l.addObserver(this);
		}
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public int getRowCount() {
		return lib.getCustomerLoans(customer).size();
	}

	@Override
	public String getColumnName(int col) {
		return columnNames[col];
	}

	public int[] getSearchColumns() {
		return searchColumns;
	}

	@Override
	public Object getValueAt(int row, int col) {
		Loan loan = lib.getCustomerLoans(customer).get(row);
		switch (col) {
			case 0 :
				return loan.getCopy().getInventoryNumber();
			case 1 :
				return loan.getCopy().getTitle().toString();
			case 2 :
					return loan.getPickupDate().getTime();
				
			case 3 :
				if (loan.isLent() && loan.getReturnDue() != null) {
					return loan.getReturnDue().getTime();
				} else {
					return loan.getReturnDate().getTime();
				}
			case 4 :
				return LoanStatus.getInstanceOf(loan);
		}
		return null;
	}

	@Override
	public void update(Observable o, Object arg1) {
		if (arg1 instanceof Loan) {
			Loan l = (Loan) arg1;
			if (l.getCustomer().equals(customer) && l.isLent()) {
				l.addObserver(this);
			}
		}

		fireTableDataChanged();
	}

	@Override
	public Loan getLoanAt(int row) {
		return lib.getCustomerLoans(customer).get(row);
	}

	@Override
	public Copy getCopyAt(int row) {
		return lib.getCustomerLoans(customer).get(row).getCopy();
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	public Class getColumnClass(int c) {
		switch (c) {
			case 0 :
				return Integer.class;
			case 2 :
			case 3 :
				return Date.class;
			case 4 :
				return LoanStatus.class;
			default :
				return String.class;
		}
	}

	public void disbandObservers() {
		lib.deleteObserver(this);
		for (Loan l : lib.getCustomerLoans(customer)) {
			l.deleteObserver(this);
		}
	}

}
